package Connections;

import java.io.IOException;
import java.net.Socket;

/**
 * Thread that will run a peer server.
 *
 * @author Rodrigo Martins Racanicci
 */
public class PeerServer extends Server implements Runnable {

    /**
     * Peer server constructor.
     *
     * @param name
     */
    public PeerServer(String name) {
        super(name);
    }

    /**
     * Put the server to accept connections.
     */
    private void acceptConnections() {
        Socket client;
        ConnectionHandler clientHandler;

        System.out.println(name + ": ready to work!");

        while (this.isAlive) {
            try {
                client = this.serverSocket.accept();
                clientHandler = new PeerHandler(client);
                registerClient(client, clientHandler);
                clientHandler.start();
                //System.out.println(name + ": new client at" + client.getInetAddress());
            } catch (IOException ex) {
                System.out.println(name + ": error accepting connection at in server socket");
            }
        }
    }

    @Override
    public void run() {
        this.acceptConnections();
    }

}
